<template>
  <div class="container">
    <!-- 全屏遮罩 - 收费课程且未订阅时显示 -->
    <div v-if="accessResolved && !canWatchVideo" class="fullscreen-overlay">
      <div class="payment-content">
        <div class="payment-icon">
          <i class="fas fa-lock"></i>
        </div>
        <h3 class="payment-title">此课程需要付费观看</h3>
        <p class="payment-description">该课程为付费内容，订阅后可观看完整视频内容</p>
        <div class="payment-price">
          <span class="price-label">课程价格：</span>
          <span class="price-value">¥{{ courseInfo.price || '99.00' }}</span>
        </div>
        <div class="payment-actions">
          <button class="subscribe-btn1" @click="showPaymentModal">
            <i class="fas fa-credit-card"></i>
            立即订阅
          </button>
          <button class="back-btn" @click="goBack">
            <i class="fas fa-arrow-left"></i>
            返回上一级
          </button>
        </div>
      </div>
    </div>

    <!-- 左侧视频区域 -->
    <div class="video-section">
      <!-- 视频头部信息 -->
      <div class="video-header">
        <h1 class="course-title">{{ courseInfo.title }}</h1>
        <div class="video-meta">
          <div class="meta-item">
            <i class="fas fa-play-circle"></i>
            <span>{{ courseInfo.viewCount }}次播放</span>
          </div>
          <div class="meta-item">
            <i class="fas fa-comment-alt"></i>

            <span>{{ courseInfo.commentCount }}条评论</span>
          </div>
          <div class="meta-item">
            <i class="fas fa-clock"></i>
            <span>{{
              courseInfo.createTime ? formatToDate(new Date(courseInfo.createTime)) : ''
            }}</span>
          </div>
        </div>
      </div>

      <!-- 视频播放区域 -->
      <div class="video-container">
        <video-play
          v-if="accessResolved && canWatchVideo"
          ref="videoPlayerRef"
          :course-info="courseInfo"
          :chapter-row="chapterInfo"
          style="height: 600px"
        />
        <div v-else-if="accessResolved" class="video-placeholder">
          <div class="placeholder-content">
            <i class="fas fa-lock"></i>
            <p>需要订阅才能观看视频</p>
          </div>
        </div>
      </div>

      <!-- 互动按钮区域 -->
      <div class="video-actions">
        <button
          class="action-btn like-btn"
          :class="{ liked: !courseInfo.isLike, active: !courseInfo.isLike }"
          @click="toggleLike"
        >
          <i class="fas fa-heart"></i>
          <span>{{ !courseInfo.isLike ? '已点赞' : '点赞' }}</span>
          <!--          <span>{{ chapterInfo.likeCount }}</span>-->
        </button>

        <button class="action-btn">
          <i class="fas fa-share-alt"></i>
          <span>分享</span>
        </button>

        <button
          v-if="courseInfo.isFree && !courseInfo.isSubscribe"
          class="action-btn subscribe-btn active"
        >
          <i class="fas fa-bell"></i>
          <span>已订阅</span>
        </button>
      </div>

      <!-- 相关标签 -->
      <!--      <div class="related-tags">-->
      <!--        <h3 class="tags-title">相关标签</h3>-->
      <!--        <div class="tags-container">-->
      <!--          <div v-for="tag in courseInfo.tags" :key="tag" class="tag">{{ tag }}</div>-->
      <!--        </div>-->
      <!--      </div>-->

      <!-- 评论区域 -->
      <div class="comments-section">
        <h3 class="section-title">
          <span>评论 ({{ chapterInfo.commentCount }})</span>
        </h3>

        <!-- 评论输入框 -->
        <div class="comment-input-area">
          <n-input
            class="comment-input"
            v-model:value="newComment"
            placeholder="写下你的评论..."
            maxlength="100"
          >
            <template #suffix>
              <n-button @click="addComment" tertiary circle type="primary">
                <template #icon>
                  <n-icon><IosSend /></n-icon>
                </template>
              </n-button>
            </template>
          </n-input>
        </div>

        <!-- 评论列表 -->
        <div class="comment-list">
          <div class="comment-item" v-for="comment in comments" :key="comment.id">
            <n-avatar class="avatar" :src="comment?.user?.avatar" round />
            <!--            <div class="avatar">-->
            <!--              {{ comment.author.charAt(0) }}-->
            <!--            </div>-->
            <div class="comment-content">
              <div class="comment-header">
                <span class="comment-author">{{ comment?.user?.username }}</span>
                <span class="badge author-badge" v-if="comment.isAuthor">作者</span>
                <span class="badge user-badge" v-if="comment.isLoginUser">我</span>
                <span class="comment-time">{{ comment.createTime }}</span>
              </div>
              <p class="comment-text">{{ comment.content }}</p>
              <div class="comment-actions">
                <!--                <div class="comment-action" @click="toggleCommentLike(comment)">-->
                <!--                  <i class="fas fa-heart" :class="{ liked: comment.isLike }"></i>-->
                <!--                  <span>{{ comment.isLike ? '已点赞' : '点赞' }}</span>-->
                <!--                  <span>{{ comment.likeCount }}</span>-->
                <!--                </div>-->
                <!--                <div class="comment-action" @click="showReplyInput(comment)">-->
                <!--                  <i class="fas fa-reply"></i>-->
                <!--                  <span>回复</span>-->
                <!--                </div>-->
                <!--                <div class="comment-action" @click="deleteCommon(comment)">-->
                <!--                  <i class="fas fa-trash-o"></i>-->
                <!--                  <span>删除</span>-->
                <!--                </div>-->
              </div>

              <!-- 回复输入框 -->
              <!--              <div class="reply-input-area" v-if="comment.showReply">-->
              <!--                <n-input-->
              <!--                  class="reply-input"-->
              <!--                  v-model:value="comment.replyText"-->
              <!--                  placeholder="写下你的回复..."-->
              <!--                  maxlength="100"-->
              <!--                >-->
              <!--                  <template #suffix>-->
              <!--                    <n-button @click="addReply(comment)" tertiary circle type="primary">-->
              <!--                      <template #icon>-->
              <!--                        <n-icon><IosSend /></n-icon>-->
              <!--                      </template>-->
              <!--                    </n-button>-->
              <!--                  </template>-->
              <!--                </n-input>-->
              <!--              </div>-->

              <!-- 回复列表 -->
              <!--              <div class="replies-section" v-if="comment.replies.length > 0">-->
              <!--                <div class="toggle-replies" @click="toggleReplies(comment)">-->
              <!--                  <i-->
              <!--                    class="fas"-->
              <!--                    :class="comment.expanded ? 'fa-chevron-up' : 'fa-chevron-down'"-->
              <!--                  ></i>-->
              <!--                  <span>{{-->
              <!--                    comment.expanded ? '收起回复' : `展开回复 (${comment.replies.length})`-->
              <!--                  }}</span>-->
              <!--                </div>-->

              <!--                <div class="reply-list" v-show="comment.expanded">-->
              <!--                  <div class="comment-item" v-for="reply in comment.replies" :key="reply.id">-->
              <!--                    <div class="avatar">-->
              <!--                      {{ reply.author.charAt(0) }}-->
              <!--                    </div>-->
              <!--                    <div class="comment-content">-->
              <!--                      <div class="comment-header">-->
              <!--                        <span class="comment-author">{{ reply.author }}</span>-->
              <!--                        <template v-if="reply.replyTo">-->
              <!--                          <span>回复</span>-->
              <!--                          <span class="comment-author">{{ reply.replyTo }}</span>-->
              <!--                        </template>-->
              <!--                        <span class="badge author-badge" v-if="reply.isAuthor">作者</span>-->
              <!--                        <span class="badge user-badge" v-if="reply.isLoginUser">我</span>-->
              <!--                        <span class="comment-time">{{ reply.time }}</span>-->
              <!--                      </div>-->
              <!--                      <p class="comment-text">{{ reply.content }}</p>-->
              <!--                      <div class="comment-actions">-->
              <!--                        <div class="comment-action" @click="toggleReplyLike(comment, reply)">-->
              <!--                          <i class="fas" :class="reply.isLike ? 'fa-heart' : 'fa-heart'"></i>-->
              <!--                          <span>{{ reply.isLike ? '已点赞' : '点赞' }}</span>-->
              <!--                          <span>{{ reply.likeCount }}</span>-->
              <!--                        </div>-->
              <!--                        <div class="comment-action" @click="showReplyInput(comment, reply)">-->
              <!--                          <i class="fas fa-reply"></i>-->
              <!--                          <span>回复</span>-->
              <!--                        </div>-->
              <!--                      </div>-->
              <!--                    </div>-->
              <!--                  </div>-->
              <!--                </div>-->
              <!--              </div>-->
            </div>
          </div>

          <!-- 空状态提示 -->
          <div v-if="!comloading && comments.length === 0" class="comment-tip"> 暂无评论 </div>

          <!-- 加载状态 -->
          <div v-if="comloading" class="comment-tip"> 加载中... </div>

          <!-- 没有更多数据提示 -->
          <div v-if="!comloading && isLastPage && comments.length > 0" class="comment-tip">
            暂无更多
          </div>
          <div
            v-if="!comloading && comments.length !== 0 && !isLastPage"
            class="load-more"
            @click="loadMoreComments"
          >
            <span>点击加载更多评论</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧信息区域 -->
    <div class="info-section">
      <!-- 作者信息 -->
      <div class="author-card" @click="toLecturerPage()">
        <div class="author-info">
          <n-avatar class="author-avatar" :src="courseInfo?.user?.avatar" round />
          <div class="author-details">
            <div class="author-name">{{ courseInfo?.user?.username || '匿名' }}</div>
            <!--            <div class="author-stats">-->
            <!--              {{ courseInfo?.authorFollowers || 0 }} 粉丝 ·-->
            <!--              {{ courseInfo?.authorCourses || 1 }} 课程-->
            <!--            </div>-->
          </div>
        </div>
        <!--        <div class="author-actions">-->
        <!--          <button class="follow-btn" :class="{ following: isFollowing }" @click="toggleFollow">-->
        <!--            {{ isFollowing ? '已关注' : '关注' }}-->
        <!--          </button>-->
        <!--          <button class="message-btn">-->
        <!--            <i class="fas fa-envelope"></i>-->
        <!--            私信-->
        <!--          </button>-->
        <!--        </div>-->
      </div>

      <!-- 课程章节 -->
      <div class="chapters-card" v-if="chapterList.length > 0">
        <h3 class="card-title">课程章节</h3>
        <div class="chapter-list">
          <div
            class="chapter-item"
            v-for="chapter in chapterList"
            :key="chapter.id"
            :class="{ active: chapterId === chapter.chapterId }"
            @click="selectChapter(chapter)"
          >
            <div class="chapter-icon">
              <i class="fas fa-play"></i>
            </div>
            <div class="chapter-info">
              <div class="chapter-title">{{ chapter.title }}</div>
              <div class="chapter-duration">{{ chapter.duration }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- 相关课程推荐 -->
      <div class="related-courses">
        <h3 class="card-title">相关推荐</h3>
        <div class="course-list">
          <!--          <div class="course-item" v-for="course in relatedCourses" :key="course.id">-->
          <!--            <div class="course-thumb">-->
          <!--              <i class="fas fa-play-circle"></i>-->
          <!--            </div>-->
          <!--            <div class="course-info">-->
          <!--              <div class="course-name">{{ course.title }}</div>-->
          <!--              <div class="course-desc">{{ course.desc }}</div>-->
          <!--            </div>-->
          <!--          </div>-->
          <div v-if="relatedCourses.length === 0" class="empty-state"> 暂无推荐 </div>
        </div>
      </div>
    </div>

    <!-- 支付方式选择弹窗 -->
    <div v-if="showPayment" class="payment-modal-overlay" @click="closePaymentModal">
      <div class="payment-modal" @click.stop>
        <div class="payment-modal-header">
          <h3>选择支付方式</h3>
          <button class="close-btn" @click="closePaymentModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="payment-modal-content">
          <div class="course-info">
            <h4>{{ courseInfo.title }}</h4>
            <div class="price-info">
              <span class="price-label">课程价格：</span>
              <span class="price-value">¥{{ courseInfo.price || '99.00' }}</span>
            </div>
          </div>
          <div class="payment-methods">
            <div
              class="payment-method"
              @click="selectPaymentMethod('2')"
              :class="{ selected: selectedPayment === '2' }"
            >
              <div class="method-icon">
                <i class="fab fa-weixin"></i>
              </div>
              <div class="method-info">
                <h4>微信支付</h4>
                <p>使用微信扫码支付</p>
              </div>
              <div class="method-radio">
                <input type="radio" name="payment" value="2" v-model="selectedPayment" />
              </div>
            </div>
            <div
              class="payment-method"
              @click="selectPaymentMethod('1')"
              :class="{ selected: selectedPayment === '1' }"
            >
              <div class="method-icon">
                <i class="fab fa-alipay"></i>
              </div>
              <div class="method-info">
                <h4>支付宝</h4>
                <p>使用支付宝扫码支付</p>
              </div>
              <div class="method-radio">
                <input type="radio" name="payment" value="1" v-model="selectedPayment" />
              </div>
            </div>
          </div>
          <div class="payment-modal-actions">
            <button class="confirm-pay-btn" @click="confirmPayment" :disabled="!selectedPayment">
              <i class="fas fa-credit-card"></i>
              确认支付 ¥{{ courseInfo.price || '99.00' }}
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 支付状态弹窗 -->
    <div v-if="showQRCode" class="qr-modal-overlay" @click="closeQRModal">
      <div class="qr-modal" @click.stop>
        <div class="qr-modal-header">
          <h3>{{ selectedPayment === '2' ? '微信支付' : '支付宝支付' }}</h3>
          <button class="close-btn" @click="closeQRModal">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <div class="qr-modal-content">
          <div class="qr-code-container">
            <div v-if="paymentLoading" class="qr-loading">
              <i class="fas fa-spinner fa-spin"></i>
              <p>正在生成支付二维码...</p>
            </div>
            <div v-else-if="qrCodeUrl" class="qr-code">
              <!--              <img :src="qrCodeUrl" alt="支付二维码" />-->
              <iframe
                :srcdoc="qrCodeUrl"
                frameborder="no"
                border="0"
                marginwidth="0"
                marginheight="0"
                scrolling="no"
                width="200"
                height="200"
                style="overflow: hidden; margin: auto; text-align: center"
              >
              </iframe>
              <p class="qr-tip"
                >请使用{{ selectedPayment === '2' ? '微信' : '支付宝' }}扫描二维码完成支付</p
              >
            </div>
            <div v-else-if="paymentStatus === 'success'" class="status-success">
              <i class="fas fa-check-circle"></i>
              <p>支付成功！正在跳转...</p>
            </div>
            <div v-else-if="paymentStatus === 'failed'" class="status-failed">
              <i class="fas fa-times-circle"></i>
              <p>支付失败，请重试</p>
            </div>
          </div>
          <div class="qr-actions">
            <button class="cancel-pay-btn" @click="cancelPayment">取消支付</button>
            <button class="refresh-qr-btn" @click="refreshQRCode" v-if="!paymentLoading">
              <i class="fas fa-refresh"></i>
              刷新二维码
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import { ref, watch, computed, onUnmounted, onMounted } from 'vue';
  import VideoPlay from './player.vue';
  import {
    getCourseDetailApi,
    getChapterDetailApi,
    getChapterListApi,
    getCommentListApi,
    addCommonApi,
    likeChapterApi,
    createPaymentOrder,
    checkPaymentStatus,
    saveVideoProgressApi,
  } from '@/api/course';
  import { useRoute, useRouter } from 'vue-router';
  import { formatToDate } from '@/utils/dateUtil';
  import { IosSend } from '@vicons/ionicons4';
  import { ResultEnum } from '@/enums/httpEnum';
  import { useMessage } from 'naive-ui';
  import { useUserStore } from '@/store/modules/user';

  const route = useRoute();
  const router = useRouter();
  const message = useMessage();
  const userStore = useUserStore();

  const courseId = ref('');
  const chapterId = ref('');
  const chapterList = ref<any[]>([]);
  // 标记课程访问权限是否计算完成，防止首次进入时闪现付费遮罩
  const accessResolved = ref(false);

  // 课程数据
  const courseInfo = ref<any>({
    // id: 1,
    // title: '人工智能：从入门到精通',
    // views: 24560,
    // commentCount: 128,
    // likeCount: 1560,
    // uploadTime: '2023年6月15日',
    // tags: ['AI开发', '人工智能', 'JavaScript', 'Web开发', '响应式设计'],
    // author: {
    //   id: 101,
    //   name: 'AI开发大师',
    //   followers: 12800,
    //   courses: 15,
    // },
    // 进度相关字段（从后端返回）
    // lastWatchedChapterId: '章节ID', // 最后观看的章节ID
    // progress: 75, // 课程整体进度百分比
    // lastWatchedTime: '2023-12-01T10:30:00Z', // 最后观看时间
    // chapterProgress: { // 各章节的详细进度信息
    //   'chapterId1': {
    //     currentTime: 120, // 当前播放时间（秒）
    //     duration: 600,    // 视频总时长（秒）
    //     progress: 20,     // 播放进度百分比
    //     lastWatchedTime: '2023-12-01T10:30:00Z'
    //   },
    //   'chapterId2': { ... }
    // }
  });

  // 计算属性：判断是否可以观看视频
  const canWatchVideo = computed(() => {
    // 如果课程是免费的（isFree为0），可以观看
    if (courseInfo.value.isFree === 0) {
      return true;
    }
    if (courseInfo.value.isSubscribe === 0) {
      return true;
    }
    return courseInfo.value.lecturerId === userStore?.info?.userId;
  });

  const chapterInfo = ref<any>({});

  // 视频播放器引用，用于获取当前播放时间
  const videoPlayerRef = ref<any>(null);

  // 监听路由变化
  watch(
    () => route.query,
    async (newParams: any) => {
      if (newParams.courseId) {
        courseId.value = newParams.courseId;
        accessResolved.value = false;
        getCourseDetail();
        getChapterList();
      }
    },
    { immediate: true }
  );

  async function getCourseDetail() {
    try {
      const data: any = await getCourseDetailApi(courseId.value);
      courseInfo.value = data;
      // 课程详情加载完成后，再允许根据 canWatchVideo 渲染
      accessResolved.value = true;
    } catch (e) {
      console.log('课程详情加载失败');
      // 出错也避免遮罩闪现
      accessResolved.value = true;
    }
  }

  async function getChapterList() {
    try {
      const params = {
        pageNum: 1,
        pageSize: 100,
        courseId: courseId.value,
      };

      const data: any = await getChapterListApi(params);
      chapterList.value = data.records || [];

      // 尝试恢复课程进度
      const hasRestored = restoreCourseProgress();

      // 如果没有恢复进度，则使用第一个章节
      if (!hasRestored) {
        chapterId.value = chapterList.value[0]?.chapterId;
      }

      getChapterDetail();
      getCommonList(true);
    } catch (error) {
      console.error('error:', error);
    } finally {
      // loading.value = false;
    }
  }

  async function getChapterDetail() {
    try {
      const data: any = await getChapterDetailApi(chapterId.value);
      chapterInfo.value = data;
    } catch (e) {
      console.log('章节详情加载失败');
    }
  }

  // 用户交互状态
  // const isFollowing = ref(false);
  const newComment = ref('');

  // 支付相关状态
  const showPayment = ref(false);
  const showQRCode = ref(false);
  const selectedPayment = ref('');
  const qrCodeUrl = ref('');
  const paymentLoading = ref(false);
  const paymentStatus = ref(''); // pending, success, failed
  const paymentOrderId = ref('');
  const paymentCheckInterval = ref<NodeJS.Timeout | null>(null); // 支付状态检查定时器引用

  // 分页参数
  const pageNum = ref(1);
  const pageSize = 10;
  const comloading = ref(false);
  const isLastPage = ref(false);
  const pages = ref(0);

  // 评论数据
  const comments = ref<any[]>([
    // {
    //   id: 1001,
    //   author: 'AI学习者',
    //   content: '这个课程太棒了！讲解得非常清晰，让我对人工智能有了全新的理解。',
    //   time: '2天前',
    //   likeCount: 24,
    //   isLike: false,
    //   isAuthor: false,
    //   isLoginUser: false,
    //   showReply: false,
    //   replyText: '',
    //   expanded: true,
    //   replies: [
    //     {
    //       id: 2001,
    //       author: 'AI爱好者',
    //       content: '同感！特别是Composition API部分，讲得太透彻了。',
    //       time: '1天前',
    //       likeCount: 8,
    //       isLike: false,
    //       isAuthor: false,
    //       isLoginUser: false,
    //       replyTo: '前端学习者',
    //     },
    //     {
    //       id: 2002,
    //       author: '前端开发大师',
    //       content: '感谢支持！后续还会推出更多实战内容。',
    //       time: '20小时前',
    //       likeCount: 15,
    //       isLike: false,
    //       isAuthor: true,
    //       isLoginUser: false,
    //       replyTo: '前端学习者',
    //     },
    //   ],
    // },
  ]);

  async function getCommonList(isRefresh = false) {
    if (comloading.value || (isLastPage.value && !isRefresh)) return;

    comloading.value = true;
    try {
      const params = {
        pageNum: pageNum.value,
        pageSize: pageSize,
        bizType: 0,
        bizId: chapterId.value,
      };

      const data: any = await getCommentListApi(params);

      let list = data.records || [];
      if (isRefresh) {
        comments.value = list;
      } else {
        comments.value = [...comments.value, ...list];
      }

      pages.value = data.pages;

      if (list.length < 10) {
        isLastPage.value = true;
      }

      if (!isLastPage.value) {
        pageNum.value++;
      }
    } catch (error) {
      console.error('error:', error);
    } finally {
      comloading.value = false;
    }
  }

  // function resetPage() {
  //   pageNum.value = 1;
  //   isLastPage.value = false;
  //   comments.value = [];
  // }

  // 相关课程数据
  const relatedCourses = ref([
    // { id: 1, title: 'React 18 核心开发实战', desc: '掌握React最新特性，构建高性能应用' },
  ]);

  // 点赞功能
  const toggleLike = async () => {
    const params = {
      bizType: 0,
      bizId: courseId.value,
    };

    const { code, data } = await likeChapterApi(params);
    if (code == ResultEnum.SUCCESS) {
      if (data) {
        courseInfo.value.isLike = 0;
        courseInfo.value.likeCount++;
      } else {
        courseInfo.value.isLike = 1;
        courseInfo.value.likeCount--;
      }
    } else {
      message.info('点赞失败，请稍后重试！');
    }
  };

  // 关注功能
  // const toggleFollow = () => {
  //   isFollowing.value = !isFollowing.value;
  // };

  const addComLoading = ref(false);

  // 添加评论
  const addComment = async () => {
    if (!newComment.value.trim()) return;

    addComLoading.value = true;

    let params = {
      content: newComment.value,
      bizType: 0,
      bizId: chapterId.value,
    };

    const { code, data } = await addCommonApi(params);
    if (code == ResultEnum.SUCCESS) {
      comments.value.unshift({
        id: data,
        time: '刚刚',
        likeCount: 0,
        isLike: false,
        isAuthor: false,
        isLoginUser: true,
        showReply: false,
        replyText: '',
        expanded: false,
        replies: [],
        user: {
          username: userStore?.info?.username,
          avatar: userStore?.info?.avatar,
        },
        ...params,
      });

      chapterInfo.value.commentCount++;
    } else {
      message.info('发表评论失败，请稍后重试！');
    }

    newComment.value = '';
  };

  // 添加回复
  // const addReply = (comment, replyTo) => {
  //   if (!comment.replyText.trim()) return;

  //   const replyObj = {
  //     id: Date.now(),
  //     author: '当前用户',
  //     content: comment.replyText,
  //     time: '刚刚',
  //     likeCount: 0,
  //     isLike: false,
  //     isAuthor: false,
  //     isLoginUser: true,
  //   };

  //   if (replyTo) {
  //     replyObj.replyTo = replyTo.author;
  //   }

  //   comment.replies.push(replyObj);
  //   comment.replyText = '';
  //   comment.showReply = false;

  //   if (!comment.expanded) {
  //     comment.expanded = true;
  //   }
  // };

  // const deleteCommon = async (row) => {
  //   const { code, data } = await deleteCommonApi(row.chapterId);
  //   if (code == ResultEnum.SUCCESS) {
  //     // comments.value.unshift({
  //     //   id: data,
  //     //   ...params,
  //     // });
  //     //
  //     // chapterInfo.value.commentCount++;
  //     message.success('评论已删除');
  //   } else {
  //     message.info('评论删除失败，请稍后重试！');
  //   }
  // };

  // 显示回复输入框
  // const showReplyInput = (comment, reply) => {
  //   comment.showReply = true;
  //   if (reply) {
  //     comment.replyText = `@${reply.author} `;
  //   }
  // };

  // 展开/收起回复
  // const toggleReplies = (comment) => {
  //   comment.expanded = !comment.expanded;
  // };

  // 评论点赞
  // const toggleCommentLike = (comment) => {
  //   comment.isLike = !comment.isLike;
  //   if (comment.isLike) {
  //     comment.likeCount++;
  //   } else {
  //     comment.likeCount--;
  //   }
  // };

  // 回复点赞
  // const toggleReplyLike = (comment, reply) => {
  //   reply.isLike = !reply.isLike;
  //   if (reply.isLike) {
  //     reply.likeCount++;
  //   } else {
  //     reply.likeCount--;
  //   }
  // };

  // 加载更多评论
  const loadMoreComments = () => {
    getCommonList();
    // // 模拟加载更多评论
    // comments.value.push({
    //   id: 1004,
    //   author: '人工智能进阶者',
    //   content: '项目实战部分非常实用，期待更多类似内容！',
    //   time: '8小时前',
    //   likeCount: 3,
    //   isLike: false,
    //   isAuthor: false,
    //   isLoginUser: false,
    //   showReply: false,
    //   replyText: '',
    //   expanded: false,
    //   replies: [],
    // });
  };

  // 选择章节
  const selectChapter = (chapter: any) => {
    // 保存当前章节进度
    saveCurrentProgress();

    chapterId.value = chapter.chapterId;
    getChapterDetail();
    getCommonList(true);
  };

  function toLecturerPage() {
    if (courseInfo.value.lecturerId) {
      router.push({ name: 'Lecturer_index', query: { id: courseInfo.value.lecturerId } });
    }
  }

  // 显示支付方式选择弹窗
  const showPaymentModal = () => {
    showPayment.value = true;
    selectedPayment.value = '';
  };

  // 关闭支付方式选择弹窗
  const closePaymentModal = () => {
    showPayment.value = false;
  };

  // 选择支付方式
  const selectPaymentMethod = (method: string) => {
    selectedPayment.value = method;
  };

  // 确认支付
  const confirmPayment = async () => {
    if (!selectedPayment.value) {
      message.warning('请选择支付方式');
      return;
    }

    closePaymentModal();
    showQRCode.value = true;
    paymentLoading.value = true;
    paymentStatus.value = 'pending';

    try {
      await generateQRCode();
    } catch (error) {
      paymentLoading.value = false;
      message.error('生成支付二维码失败');
    }
  };

  // 生成支付二维码
  const generateQRCode = async () => {
    try {
      const orderData = {
        courseId: courseInfo.value.courseId,
        payType: selectedPayment.value,
      };

      // 调用真实的支付API
      const data = await createPaymentOrder(orderData);
      console.log('支付订单数据:', data);

      paymentOrderId.value = data.orderNo;
      // // 处理支付二维码
      if (data.orderString) {
        qrCodeUrl.value = data.orderString;
        paymentLoading.value = false;
        // 开始检查支付状态
        startPaymentStatusCheck();
      } else {
        message.error('二维码生成失败');
        return;
      }
    } catch (error) {
      paymentLoading.value = false;
      throw error;
    }
  };

  // 开始检查支付状态
  const startPaymentStatusCheck = () => {
    // 如果已有定时器在运行，先清除
    if (paymentCheckInterval.value) {
      clearInterval(paymentCheckInterval.value);
    }

    paymentCheckInterval.value = setInterval(async () => {
      try {
        // 调用真实的支付状态检查API
        const data = await checkPaymentStatus(paymentOrderId.value);

        if (data.status === 1) {
          // 支付成功
          paymentStatus.value = 'success';
          if (paymentCheckInterval.value) {
            clearInterval(paymentCheckInterval.value);
            paymentCheckInterval.value = null;
          }
          setTimeout(() => {
            closeQRModal();
            handlePaymentSuccess();
          }, 2000);
        } else if (data.status === 0) {
          // 待支付，继续轮询
          console.log('等待支付中...');
        } else {
          // 支付失败或其他状态
          paymentStatus.value = 'failed';
          if (paymentCheckInterval.value) {
            clearInterval(paymentCheckInterval.value);
            paymentCheckInterval.value = null;
          }
        }
      } catch (error) {
        console.error('检查支付状态失败:', error);
        // 网络错误时继续轮询，不停止
      }
    }, 3000); // 每3秒检查一次

    // 15分钟后自动停止检查
    setTimeout(() => {
      if (paymentCheckInterval.value) {
        clearInterval(paymentCheckInterval.value);
        paymentCheckInterval.value = null;
      }
      if (paymentStatus.value === 'pending') {
        paymentStatus.value = 'failed';
      }
    }, 900000);
  };

  // 支付成功处理
  const handlePaymentSuccess = async () => {
    try {
      // 支付成功后直接更新课程订阅状态，不需要调用订阅接口
      courseInfo.value.isSubscribe = 0; // 设置为已订阅状态
      message.success('支付成功！现在可以观看完整课程内容了');
    } catch (error) {
      message.error('支付成功，但状态更新失败，请刷新页面');
    }
  };

  // 关闭二维码弹窗
  const closeQRModal = () => {
    // 清除支付状态检查定时器
    if (paymentCheckInterval.value) {
      clearInterval(paymentCheckInterval.value);
      paymentCheckInterval.value = null;
    }

    showQRCode.value = false;
    qrCodeUrl.value = '';
    paymentStatus.value = '';
    paymentOrderId.value = '';
  };

  // 取消支付
  const cancelPayment = () => {
    closeQRModal();
    message.info('已取消支付');
  };

  // 刷新二维码
  const refreshQRCode = async () => {
    // 清除之前的定时器
    if (paymentCheckInterval.value) {
      clearInterval(paymentCheckInterval.value);
      paymentCheckInterval.value = null;
    }

    paymentLoading.value = true;
    paymentStatus.value = 'pending';
    try {
      await generateQRCode();
    } catch (error) {
      paymentLoading.value = false;
      message.error('刷新二维码失败');
    }
  };

  // 返回课程列表
  const goBack = () => {
    router.go(-1); // 返回上一页
  };

  // 保存当前播放进度
  const saveCurrentProgress = async () => {
    if (chapterId.value && courseId.value && videoPlayerRef.value) {
      try {
        // 从视频播放器获取当前播放时间
        const currentTime = videoPlayerRef.value.getCurrentTime?.() || 0;
        const duration = videoPlayerRef.value.getDuration?.() || chapterInfo.value.duration || 0;

        // 如果视频总时长低于30秒，则currentTime和progress传值为0
        const finalCurrentTime = duration < 30 ? 0 : Math.floor(currentTime);
        const finalProgress =
          duration < 30 ? 0 : duration > 0 ? Math.round((currentTime / duration) * 100) : 0;

        const progressData = {
          courseId: courseId.value,
          chapterId: chapterId.value,
          currentTime: finalCurrentTime,
          duration: Math.floor(duration),
          progress: finalProgress,
        };

        await saveVideoProgressApi(progressData);
        console.log(`保存当前章节进度: ${currentTime.toFixed(1)}s / ${duration.toFixed(1)}s`);
      } catch (error) {
        console.warn('保存章节进度失败:', error);
      }
    }
  };

  // 恢复课程进度（从courseInfo中获取）
  const restoreCourseProgress = () => {
    if (courseInfo.value && courseInfo.value.lastWatchedChapterId) {
      const targetChapter = chapterList.value.find(
        (chapter) => chapter.chapterId === courseInfo.value.lastWatchedChapterId
      );
      if (targetChapter) {
        chapterId.value = courseInfo.value.lastWatchedChapterId;
        console.log(`恢复课程进度到章节: ${targetChapter.title}`);
        return true; // 表示已恢复进度
      }
    }
    return false; // 没有可恢复的进度
  };

  // 页面关闭时保存进度
  const handleBeforeUnload = () => {
    saveCurrentProgress();
  };

  // 组件销毁时保存进度
  onUnmounted(() => {
    saveCurrentProgress();
    // 移除事件监听器
    window.removeEventListener('beforeunload', handleBeforeUnload);
  });

  // 添加页面关闭事件监听
  onMounted(() => {
    window.addEventListener('beforeunload', handleBeforeUnload);
  });

  // function timestampFormat(dateStr: any) {
  //   if (!dateStr) return '';
  //   const timestamp = new Date(dateStr).getTime() / 1000;

  //   function zeroize(num) {
  //     return (String(num).length == 1 ? '0' : '') + num;
  //   }

  //   var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
  //   var timestampDiff = curTimestamp - timestamp; // 参数时间戳与当前时间戳相差秒数

  //   var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
  //   var tmDate = new Date(timestamp * 1000); // 参数时间戳转换成的日期对象

  //   var Y = tmDate.getFullYear(),
  //     m = tmDate.getMonth() + 1,
  //     d = tmDate.getDate();
  //   var H = tmDate.getHours(),
  //     i = tmDate.getMinutes(),
  //     s = tmDate.getSeconds();

  //   if (timestampDiff < 60) {
  //     // 一分钟以内
  //     return '刚刚';
  //   } else if (timestampDiff < 3600) {
  //     // 一小时前之内
  //     return Math.floor(timestampDiff / 60) + '分钟前';
  //   } else if (
  //     curDate.getFullYear() == Y &&
  //     curDate.getMonth() + 1 == m &&
  //     curDate.getDate() == d
  //   ) {
  //     return '今天' + zeroize(H) + ':' + zeroize(i);
  //   } else {
  //     var newDate = new Date((curTimestamp - 86400) * 1000); // 参数中的时间戳加一天转换成的日期对象
  //     if (newDate.getFullYear() == Y && newDate.getMonth() + 1 == m && newDate.getDate() == d) {
  //       return '昨天' + zeroize(H) + ':' + zeroize(i);
  //     } else if (curDate.getFullYear() == Y) {
  //       return zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
  //     } else {
  //       return Y + '年' + zeroize(m) + '月' + zeroize(d) + '日 ' + zeroize(H) + ':' + zeroize(i);
  //     }
  //   }
  // }
</script>

<style lang="less" scoped>
  .container {
    margin: 0 auto;
    display: flex;
    gap: 20px;
  }

  .video-section {
    flex: 3;
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    overflow: hidden;
    padding: 20px;
  }

  .info-section {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 20px;
  }

  /* 视频头部信息 */
  .video-header {
    margin-bottom: 20px;
    padding-bottom: 15px;
    border-bottom: 1px solid #eee;
  }

  .course-title {
    font-size: 24px;
    margin-bottom: 12px;
    color: #2c3e50;
  }

  .video-meta {
    display: flex;
    gap: 20px;
    color: #666;
    font-size: 14px;
  }

  .meta-item {
    display: flex;
    align-items: center;
    gap: 5px;
  }

  /* 视频播放器区域 */
  .video-container {
    position: relative;
    border-radius: 8px;
    overflow: hidden;
    height: 600px;
    //display: flex;
    //justify-content: center;
    //align-items: center;
    //background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
  }

  .video-player {
    width: 100%;
    height: 100%;
    object-fit: cover;
    z-index: 1;
  }

  .video-overlay {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: white;
    z-index: 2;
    background: rgba(0, 0, 0, 0.3);
  }

  .play-icon {
    font-size: 80px;
    opacity: 0.8;
    cursor: pointer;
    transition: all 0.3s ease;
    margin-bottom: 20px;
  }

  .play-icon:hover {
    transform: scale(1.1);
    opacity: 1;
  }

  .video-title {
    font-size: 24px;
    font-weight: bold;
    text-align: center;
    max-width: 80%;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5);
  }

  /* 互动按钮区域 */
  .video-actions {
    display: flex;
    padding: 15px 0;
    gap: 20px;
    border-bottom: 1px solid #eee;
  }

  .action-btn {
    display: flex;
    align-items: center;
    gap: 8px;
    background: none;
    border: none;
    cursor: pointer;
    font-size: 16px;
    color: #555;
    transition: all 0.3s ease;
    padding: 8px 15px;
    border-radius: 6px;
  }

  .action-btn:hover {
    background: #f5f7fa;
  }

  .like-btn.active {
    color: #ff4d4f;
  }

  .subscribe-btn.active {
    color: #1890ff;
    background: #e6f7ff;
  }

  .action-btn i {
    font-size: 20px;
    transition: transform 0.3s;
  }

  .action-btn.liked i {
    animation: pulse 0.5s;
  }

  .liked {
    color: #e74c3c;
    border-color: #fadbd8;
    background: #fdedec;
  }

  @keyframes pulse {
    0% {
      transform: scale(1);
    }
    50% {
      transform: scale(1.3);
    }
    100% {
      transform: scale(1);
    }
  }

  /* 标签区域 */
  .related-tags {
    margin-top: 25px;
  }

  .tags-title {
    font-size: 18px;
    margin-bottom: 15px;
    color: #2c3e50;
  }

  .tags-container {
    display: flex;
    flex-wrap: wrap;
    gap: 10px;
  }

  .tag {
    padding: 8px 15px;
    background: #e8f4fd;
    border-radius: 20px;
    color: #3498db;
    font-size: 14px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .tag:hover {
    background: #d6eaf8;
    transform: translateY(-2px);
  }

  /* 评论区域 */
  .comments-section {
    margin-top: 25px;
  }

  .section-title {
    font-size: 18px;
    margin-bottom: 15px;
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .comment-input-area {
    display: flex;
    gap: 10px;
    margin-bottom: 30px;
  }

  .comment-input {
    padding: 10px 0;
  }

  // .send-btn {
  //   background: #1890ff;
  //   color: white;
  //   border: none;
  //   border-radius: 8px;
  //   padding: 0 25px;
  //   cursor: pointer;
  //   font-weight: 500;
  //   transition: background 0.3s;
  // }

  //.send-btn:hover {
  //  background: #40a9ff;
  //}

  .comment-list {
    display: flex;
    flex-direction: column;
    gap: 25px;
  }

  .comment-item {
    display: flex;
    gap: 15px;
    background: #f9fbfd;
    border: 1px solid #eef2f7;
    padding: 20px;
    border-radius: 8px;
  }

  .avatar {
    width: 40px;
    height: 40px;
  }

  .comment-content {
    flex: 1;
  }

  .comment-header {
    display: flex;
    align-items: center;
    gap: 10px;
    margin-bottom: 5px;
  }

  .comment-author {
    font-weight: 600;
    color: #2c3e50;
  }

  .badge {
    font-size: 12px;
    padding: 2px 6px;
    border-radius: 3px;
  }

  .author-badge {
    background: #fff7e6;
    color: #fa8c16;
  }

  .user-badge {
    background: #e6f7ff;
    color: #1890ff;
  }

  .comment-time {
    color: #999;
    font-size: 13px;
  }

  .comment-text {
    margin-bottom: 10px;
    line-height: 1.5;
  }

  .comment-actions {
    display: flex;
    gap: 15px;
    color: #666;
    font-size: 14px;
  }

  .comment-action {
    display: flex;
    align-items: center;
    gap: 5px;
    cursor: pointer;
    transition: color 0.3s;
  }

  .comment-action:hover {
    color: #1890ff;
  }

  .replies-section {
    margin-top: 15px;
    padding-left: 20px;
    border-left: 2px solid #eee;
  }

  .toggle-replies {
    display: flex;
    align-items: center;
    gap: 5px;
    color: #1890ff;
    margin-bottom: 15px;
    cursor: pointer;
    font-size: 14px;
    font-weight: 500;
  }

  .reply-input-area {
    margin-top: 10px;
    display: flex;
    gap: 10px;
  }

  .reply-input {
    padding: 8px 0;
  }

  .reply-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
    margin-top: 10px;
  }

  .comment-tip {
    text-align: center;
    height: 60px;
    line-height: 60px;
    color: #999;
    font-size: 16px;
  }

  .load-more {
    text-align: center;
    color: #1890ff;
    padding: 10px;
    cursor: pointer;
    font-weight: 500;
    margin-top: 10px;
  }

  /* 右侧信息区域 */
  .author-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 20px;
  }

  .author-info {
    display: flex;
    gap: 15px;
    align-items: center;
  }

  .author-avatar {
    width: 60px;
    height: 60px;
  }

  .author-details {
    flex: 1;
  }

  .author-name {
    font-weight: 600;
    font-size: 18px;
    margin-bottom: 5px;
  }

  .author-stats {
    color: #666;
    font-size: 14px;
  }

  .author-actions {
    margin-top: 20px;
    display: flex;
    gap: 10px;
  }

  .follow-btn,
  .message-btn {
    //flex: 1;
    padding: 8px 0;
    border-radius: 6px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s;
  }

  .follow-btn {
    background: #1890ff;
    color: white;
    border: none;
  }

  .follow-btn:hover {
    background: #40a9ff;
  }

  .follow-btn.following {
    background: #f5f5f5;
    color: #666;
    border: 1px solid #ddd;
  }

  .message-btn {
    background: white;
    border: 1px solid #ddd;
    color: #555;
  }

  .message-btn:hover {
    border-color: #1890ff;
    color: #1890ff;
  }

  /* 章节列表 */
  .chapters-card {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 25px;
  }

  .card-title {
    font-size: 18px;
    margin-bottom: 20px;
    color: #2c3e50;
  }

  .chapter-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .chapter-item {
    display: flex;
    align-items: center;
    gap: 15px;
    padding: 12px 15px;
    border-radius: 8px;
    background: #f8fafc;
    border: 1px solid #edf2f7;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .chapter-item:hover {
    background: #ebf5fb;
    border-color: #d6eaf8;
  }

  .chapter-item.active {
    background: #e1f0fa;
    border-color: #3498db;
  }

  .chapter-icon {
    width: 40px;
    height: 40px;
    border-radius: 8px;
    background: #e3f2fd;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #3498db;
  }

  .chapter-info {
    flex: 1;
  }

  .chapter-title {
    font-weight: 500;
    margin-bottom: 3px;
  }

  .chapter-duration {
    font-size: 13px;
    color: #7f8c8d;
  }

  /* 推荐视频列表 */
  .related-courses {
    background: white;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    padding: 25px;
  }

  .course-list {
    display: flex;
    flex-direction: column;
    gap: 15px;
  }

  .course-item {
    display: flex;
    gap: 15px;
    cursor: pointer;
    transition: transform 0.3s ease;
  }

  .course-item:hover {
    transform: translateX(5px);
  }

  .course-thumb {
    width: 120px;
    height: 70px;
    border-radius: 6px;
    background: linear-gradient(135deg, #6a11cb 0%, #2575fc 100%);
    flex-shrink: 0;
    display: flex;
    align-items: center;
    justify-content: center;
    color: white;
    font-size: 24px;
  }

  .course-info {
    flex: 1;
  }

  .course-name {
    font-weight: 500;
    margin-bottom: 5px;
    color: #2c3e50;
  }

  .course-desc {
    font-size: 13px;
    color: #7f8c8d;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }

  /* 响应式设计 */
  @media (max-width: 992px) {
    .container {
      flex-direction: column;
    }

    .video-section,
    .info-section {
      width: 100%;
    }
  }

  .empty-state {
    text-align: center;
    padding: 60px 20px;
    margin-bottom: 15px;
    font-size: 16px;
    color: #95a5a6;
  }

  /* 全屏遮罩 */
  .fullscreen-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(102, 126, 234, 0.8);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 9999;
    backdrop-filter: blur(5px);
  }

  .payment-content {
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    border-radius: 16px;
    padding: 40px;
    text-align: center;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
    max-width: 400px;
    width: 90%;
    margin: 20px;
  }

  .payment-icon {
    font-size: 48px;
    color: #ff6b6b;
    margin-bottom: 20px;
  }

  .payment-title {
    font-size: 24px;
    font-weight: 700;
    color: #2c3e50;
    margin-bottom: 12px;
  }

  .payment-description {
    color: #7f8c8d;
    font-size: 16px;
    line-height: 1.5;
    margin-bottom: 24px;
  }

  .payment-price {
    background: #f8f9fa;
    border-radius: 8px;
    padding: 16px;
    margin-bottom: 24px;
    border: 2px solid #e9ecef;
  }

  .price-label {
    color: #6c757d;
    font-size: 14px;
  }

  .price-value {
    color: #e74c3c;
    font-size: 24px;
    font-weight: 700;
    margin-left: 8px;
  }

  .payment-actions {
    display: flex;
    flex-direction: column;
    gap: 12px;
  }

  .subscribe-btn1 {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    color: white;
    border: none;
    border-radius: 8px;
    padding: 12px 24px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .subscribe-btn1:hover {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
  }

  .back-btn {
    background: #f8f9fa;
    color: #6c757d;
    border: 1px solid #dee2e6;
    border-radius: 8px;
    padding: 12px 24px;
    font-size: 16px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .back-btn:hover {
    background: #e9ecef;
    border-color: #adb5bd;
  }

  /* 视频占位符 */
  .video-placeholder {
    height: 600px;
    background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    border-radius: 8px;
    border: 2px dashed #d1d5db;
  }

  .placeholder-content {
    text-align: center;
    color: #6b7280;
  }

  .placeholder-content i {
    font-size: 48px;
    margin-bottom: 16px;
    color: #9ca3af;
  }

  .placeholder-content p {
    font-size: 18px;
    font-weight: 500;
    margin: 0;
  }

  /* 支付方式选择弹窗 */
  .payment-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10000;
    backdrop-filter: blur(5px);
  }

  .payment-modal {
    background: white;
    border-radius: 16px;
    width: 90%;
    max-width: 500px;
    max-height: 80vh;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  }

  .payment-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #e5e7eb;
  }

  .payment-modal-header h3 {
    margin: 0;
    font-size: 20px;
    font-weight: 600;
    color: #111827;
  }

  .close-btn {
    background: none;
    border: none;
    font-size: 18px;
    color: #6b7280;
    cursor: pointer;
    padding: 4px;
    border-radius: 4px;
    transition: all 0.2s;
  }

  .close-btn:hover {
    background: #f3f4f6;
    color: #374151;
  }

  .payment-modal-content {
    padding: 24px;
  }

  .course-info {
    margin-bottom: 24px;
    padding: 16px;
    background: #f9fafb;
    border-radius: 8px;
  }

  .course-info h4 {
    margin: 0 0 8px 0;
    font-size: 16px;
    font-weight: 600;
    color: #111827;
  }

  .price-info {
    display: flex;
    align-items: center;
    gap: 8px;
  }

  .price-label {
    color: #6b7280;
    font-size: 14px;
  }

  .price-value {
    color: #e74c3c;
    font-size: 18px;
    font-weight: 700;
  }

  .payment-methods {
    margin-bottom: 24px;
  }

  .payment-method {
    display: flex;
    align-items: center;
    padding: 16px;
    border: 2px solid #e5e7eb;
    border-radius: 12px;
    margin-bottom: 12px;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .payment-method:hover {
    border-color: #d1d5db;
    background: #f9fafb;
  }

  .payment-method.selected {
    border-color: #3b82f6;
    background: #eff6ff;
  }

  .method-icon {
    width: 48px;
    height: 48px;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 16px;
    font-size: 24px;
  }

  .payment-method:first-child .method-icon {
    background: #00c851;
    color: white;
  }

  .payment-method:last-child .method-icon {
    background: #1677ff;
    color: white;
  }

  .method-info {
    flex: 1;
  }

  .method-info h4 {
    margin: 0 0 4px 0;
    font-size: 16px;
    font-weight: 600;
    color: #111827;
  }

  .method-info p {
    margin: 0;
    font-size: 14px;
    color: #6b7280;
  }

  .method-radio input {
    width: 20px;
    height: 20px;
    accent-color: #3b82f6;
  }

  .confirm-pay-btn {
    width: 100%;
    background: linear-gradient(135deg, #3b82f6 0%, #1d4ed8 100%);
    color: white;
    border: none;
    border-radius: 12px;
    padding: 16px;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.3s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
  }

  .confirm-pay-btn:hover:not(:disabled) {
    transform: translateY(-2px);
    box-shadow: 0 8px 20px rgba(59, 130, 246, 0.4);
  }

  .confirm-pay-btn:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }

  /* 二维码弹窗 */
  .qr-modal-overlay {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 10001;
    backdrop-filter: blur(5px);
  }

  .qr-modal {
    background: white;
    border-radius: 16px;
    width: 90%;
    max-width: 400px;
    overflow: hidden;
    box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
  }

  .qr-modal-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 24px;
    border-bottom: 1px solid #e5e7eb;
  }

  .qr-modal-header h3 {
    margin: 0;
    font-size: 18px;
    font-weight: 600;
    color: #111827;
  }

  .qr-modal-content {
    padding: 24px;
    text-align: center;
  }

  .qr-code-container {
    margin-bottom: 24px;
  }

  .qr-loading {
    padding: 40px 20px;
    color: #6b7280;
  }

  .qr-loading i {
    font-size: 32px;
    margin-bottom: 12px;
    color: #3b82f6;
  }

  .qr-code img {
    width: 200px;
    height: 200px;
    border-radius: 8px;
    border: 1px solid #e5e7eb;
  }

  .qr-tip {
    margin-top: 16px;
    color: #6b7280;
    font-size: 14px;
  }

  .payment-redirect {
    padding: 40px 20px;
    text-align: center;
    color: #3b82f6;
  }

  .payment-redirect i {
    font-size: 48px;
    margin-bottom: 16px;
    color: #3b82f6;
  }

  .payment-redirect p {
    margin: 8px 0;
    font-size: 16px;
    font-weight: 500;
  }

  .redirect-tip {
    font-size: 14px !important;
    color: #6b7280 !important;
    font-weight: normal !important;
  }

  .qr-error {
    padding: 40px 20px;
    color: #ef4444;
  }

  .qr-error i {
    font-size: 32px;
    margin-bottom: 12px;
  }

  .payment-status {
    margin-bottom: 24px;
    padding: 16px;
    border-radius: 8px;
  }

  .status-pending {
    background: #fef3c7;
    color: #d97706;
  }

  .status-success {
    background: #d1fae5;
    color: #059669;
  }

  .status-failed {
    background: #fee2e2;
    color: #dc2626;
  }

  .payment-status i {
    font-size: 24px;
    margin-bottom: 8px;
  }

  .payment-status p {
    margin: 0;
    font-weight: 500;
  }

  .qr-actions {
    display: flex;
    gap: 12px;
  }

  .cancel-pay-btn,
  .refresh-qr-btn {
    flex: 1;
    padding: 12px;
    border-radius: 8px;
    font-weight: 500;
    cursor: pointer;
    transition: all 0.3s ease;
  }

  .cancel-pay-btn {
    background: #f3f4f6;
    color: #6b7280;
    border: 1px solid #d1d5db;
  }

  .cancel-pay-btn:hover {
    background: #e5e7eb;
  }

  .refresh-qr-btn {
    background: #3b82f6;
    color: white;
    border: none;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 6px;
  }

  .refresh-qr-btn:hover {
    background: #2563eb;
  }
</style>
